package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.WarehouseReceiptDetailQueryDTO;
import com.intelligent.pojo.*;
import com.intelligent.mapper.WarehouseReceiptDetailMapper;
import com.intelligent.service.*;
import com.intelligent.vo.WarehouseReceiptDetailVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;

/**
 * 入库单明细服务实现
 */
@Service
public class WarehouseReceiptDetailServiceImpl extends ServiceImpl<WarehouseReceiptDetailMapper, WarehouseReceipt>
    implements WarehouseReceiptDetailService {

    @Autowired
    private ProductService productService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private TUserService userService;

    @Autowired
    private UnitService unitService;

    @Override
    public IPage<WarehouseReceiptDetailVO> pageList(WarehouseReceiptDetailQueryDTO query) {
        // 1. 处理产品名称和类型查询条件
        Set<Long> productIds = new HashSet<>();

        // 如果指定了产品类型，先查询符合类型的产品ID
        if (query.getCategory() != null) {
            LambdaQueryWrapper<Product> categoryQuery = new LambdaQueryWrapper<>();
            categoryQuery.eq(Product::getCategory, query.getCategory());
            List<Long> categoryProductIds = productService.list(categoryQuery)
                .stream()
                .map(Product::getProductId)
                .collect(Collectors.toList());
            productIds.addAll(categoryProductIds);

            // 如果指定类型下没有产品，直接返回空结果
            if (productIds.isEmpty()) {
                return new Page<>();
            }
        }

        // 如果指定了产品名称，查询符合名称的产品ID
        if (StringUtils.isNotBlank(query.getProductName())) {
            LambdaQueryWrapper<Product> nameQuery = new LambdaQueryWrapper<>();
            nameQuery.like(Product::getProductName, query.getProductName());
            List<Long> nameProductIds = productService.list(nameQuery)
                .stream()
                .map(Product::getProductId)
                .collect(Collectors.toList());

            if (productIds.isEmpty()) {
                // 如果之前没有类型过滤，直接使用名称查询结果
                productIds.addAll(nameProductIds);
            } else {
                // 如果之前有类型过滤，取交集
                productIds.retainAll(nameProductIds);
                if (productIds.isEmpty()) {
                    return new Page<>();
                }
            }
        }
            // 构建产品查询条件
            LambdaQueryWrapper<Product> productQuery = new LambdaQueryWrapper<>();

        // 如果没有符合条件的商品，直接返回空结果
        if (CollectionUtils.isEmpty(productIds)) {
            return new Page<>();
        }

        // 2. 设置分页参数
        Page<WarehouseReceipt> page = new Page<>(
            query.getPageNum() != null ? query.getPageNum() : 1,
            query.getPageSize() != null ? query.getPageSize() : 10
        );

        // 3. 构建入库单查询条件
        LambdaQueryWrapper<WarehouseReceipt> wrapper = new LambdaQueryWrapper<>();

        // 入库单号模糊查询
        if (StringUtils.isNotBlank(query.getReceiptNo())) {
            wrapper.like(WarehouseReceipt::getReceiptNo, query.getReceiptNo());
        }

        // 仓库ID查询
        if (query.getWarehouseId() != null) {
            wrapper.eq(WarehouseReceipt::getWarehouseId, query.getWarehouseId());
        }

        // 产品ID查询条件
        if (!CollectionUtils.isEmpty(productIds)) {
            wrapper.in(WarehouseReceipt::getProductId, productIds);
        }

        // 4. 执行分页查询
        IPage<WarehouseReceipt> receiptPage = this.page(page, wrapper);

        // 5. 转换为VO
        return receiptPage.convert(receipt -> {
            WarehouseReceiptDetailVO vo = new WarehouseReceiptDetailVO();
            BeanUtils.copyProperties(receipt, vo);

            // 设置产品信息
            if (receipt.getProductId() != null) {
                Product product = productService.getById(receipt.getProductId());
                if (product != null) {
                    vo.setProductId(product.getProductId());
                    vo.setProductName(product.getProductName());
                    vo.setProductCode(product.getProductCode());
                    vo.setSpecification(product.getSpecification());
                    vo.setCategory(product.getCategory());
                }
            }

            // 设置仓库信息
            if (receipt.getWarehouseId() != null) {
                Warehouse warehouse = warehouseService.getById(receipt.getWarehouseId());
                if (warehouse != null) {
                    vo.setWarehouseName(warehouse.getWarehouseName());
                }
            }

            // 设置用户信息
            if (receipt.getUId() != null) {
                TUser user = userService.getById(receipt.getUId());
                if (user != null) {
                    vo.setUsername(user.getUsername());
                }
            }

            if (receipt.getUnitId() != null) {
                Unit unit = unitService.getById(receipt.getUnitId());
                if (unit != null) {
                    vo.setUnitName(unit.getUnitName());
                }
            }

            return vo;
        });
    }
}
